package com.myapp.Activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;
import com.myapp.Activity.AirLink.AirlinkChooseActivity;
import com.myapp.Activity.AirLink.AirlinkingActivity;
import com.myapp.Data.GizManger;
import com.myapp.R;
import com.myapp.RN.DeviceActivity;
import com.myapp.utils.PreferencesUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.myapp.Activity.AirLink.AirlinkingActivity.MAC;
import static com.myapp.Activity.LoginActivity.TOKEN;
import static com.myapp.Activity.LoginActivity.UID;
import static com.myapp.MainApplication.PRODUCT_S;

public class DeviceListActivity extends BaseActivity {
    private static final String TAG = "DeviceListActivity";
    @BindView(R.id.btn_add_device)
    Button btnAddDevice;
    @BindView(R.id.recycle_device)
    RecyclerView recycleDevice;
    @BindView(R.id.ll_no_device)
    LinearLayout llNoDevice;
    @BindView(R.id.ll_have_device)
    LinearLayout llHaveDevice;

    private DeviceAdapter mAdapter;
    List<GizWifiDevice> devices;
    String uid;
    String token;
    String mac;
    String did;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        ButterKnife.bind(this);
        recycleDevice.setLayoutManager(new LinearLayoutManager(this));
        devices = new ArrayList<>();
        mAdapter = new DeviceAdapter(devices);
        recycleDevice.setAdapter(mAdapter);

        // 主动刷新绑定设备列表、指定筛选的设备productKey
        uid = PreferencesUtil.getInstance(getApplicationContext()).getString(UID, null);
        token = PreferencesUtil.getInstance(getApplicationContext()).getString(TOKEN, null);
        mac = PreferencesUtil.getInstance(getApplicationContext()).getString(MAC, null);

        Log.i(TAG, "onCreate: "+"uid:"+uid+" token:"+token+" mac:"+mac);

        GizWifiSDK.sharedInstance().setListener(mListener);
        if (uid != null && token != null) {
            GizWifiSDK.sharedInstance().getBoundDevices(uid, token);
        }
    }


    @OnClick({R.id.btn_add_device, R.id.recycle_device})
    void OnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add_device:
                final Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
                View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_content_normal, null);
                bottomDialog.setContentView(contentView);
                ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
                layoutParams.width = getResources().getDisplayMetrics().widthPixels;
                contentView.setLayoutParams(layoutParams);
                bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
                bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
                bottomDialog.show();
                bottomDialog.findViewById(R.id.btn_bottom_airLink).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getApplicationContext(), AirlinkChooseActivity.class);
                        startActivity(intent);
                    }
                });

                bottomDialog.findViewById(R.id.btn_bottom_softAp).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getApplicationContext(), AirlinkChooseActivity.class);
                        startActivity(intent);
                    }
                });

                bottomDialog.findViewById(R.id.btn_bottom_cancer).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       bottomDialog.dismiss();
//                        Intent intent = new Intent(getApplicationContext(),DeviceActivity.class);
//                        startActivity(intent);
                    }
                });
//                      Intent back = new Intent(this,MainActivity.class);
//                      startActivity(back);
                break;


        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: "+"执行");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private class DeviceAdapter extends RecyclerView.Adapter<DeviceHolder> {
        private List<GizWifiDevice> mDevices;

        public DeviceAdapter(List<GizWifiDevice> devices) {
            mDevices = devices;
        }

        @NonNull
        @Override
        public DeviceHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
            return new DeviceHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(@NonNull DeviceHolder deviceHolder, int position) {
            GizWifiDevice device = mDevices.get(position);
            deviceHolder.bind(device);
        }

        @Override
        public int getItemCount() {
            return mDevices.size();
        }
    }


    private class DeviceHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {
        private TextView mTitleTextView;
        private GizWifiDevice mDevice;
        private View view;
        private Button mUnbind;

        public void bind(GizWifiDevice device) {

            mDevice = device;
            mTitleTextView.setText(mDevice.getProductName());
            mDevice.setListener(new GizWifiDeviceListener() {
                @Override
                public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {
                    if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                        // 订阅或解除订阅成功
//                        DataManger.status = true;
//                        DataManger.getInstance().setDevice(mDevice);
//
                        GizManger.getInstance().setDevice(mDevice);

                        Log.i(TAG, device.getProductName() + "订阅成功：");
                    } else {
                        // 失败
                        Log.i(TAG, device.getProductName() + "订阅失败：");
                    }
                }
            });
        }

        public DeviceHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item, parent, false));

            mTitleTextView = (TextView) itemView.findViewById(R.id.machine_name);
            view = itemView.findViewById(R.id.view_device_item);
            view.setOnClickListener(this);
            mUnbind = itemView.findViewById(R.id.btn_item_delete);
            mUnbind.setOnClickListener(this);
        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.view_device_item:
                    Log.i(TAG, "onClick: "+"进入设备页面");
                    mDevice.setSubscribe(PRODUCT_S, true);
                    Intent intent = new Intent(getApplicationContext(),DeviceActivity.class);
                    startActivity(intent);
                    break;
                case R.id.btn_item_delete:
                   // 删除
                    did=mDevice.getDid();
                    AlertDialog.Builder builder = new AlertDialog.Builder(DeviceListActivity.this);
                    builder.setTitle("提示") //标题
                            .setMessage("你确定要删除设备?") //提示内容
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() { //确定
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    GizWifiSDK.sharedInstance().unbindDevice(uid, token, did);
                                }
                            })
                            .setNegativeButton("取消", null);
                    builder.show();
                    break;
                default:
                    break;
            }

        }


    }


    // 接收设备列表变化上报，刷新UI
    GizWifiSDKListener mListener = new GizWifiSDKListener() {

        @Override
        public void didDiscovered(GizWifiErrorCode result, List<GizWifiDevice> deviceList) {
            // 提示错误原因
            if (result != GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                //Log.i(TAG, "result: " + result.name());
            }
            // 显示变化后的设备列表
            Log.i(TAG, "discovered deviceList: " + deviceList);
            //一开始的代码
//            for(GizWifiDevice gizWifiDevice : deviceList) {
//                if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOffline) {
//                    Log.i(TAG, "didDiscovered: 到了");
//                    deviceList.remove(gizWifiDevice);
//                }
//            }
            List<GizWifiDevice> List = new ArrayList<>();
            for (int i = 0; i < deviceList.size(); i++) {
                GizWifiDevice gizWifiDevice = deviceList.get(i);
                //if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline||gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled){
                if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline && gizWifiDevice.isBind()) {
                    List.add(gizWifiDevice);
                }
                if (gizWifiDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOffline || !gizWifiDevice.isBind()) {
                    List.remove(gizWifiDevice);
                }
            }

            updateUI(List);
        }

        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 解绑成功
                Log.i(TAG, "didUnbindDevice 成功: " + did);
            } else {

                Log.i(TAG, "didUnbindDevice 失败: " + did);
            }
        }
    };

    private void updateUI(List<GizWifiDevice> deviceList) {
        devices.clear();
        devices.addAll(deviceList);
        mAdapter.notifyDataSetChanged();
        if (devices.isEmpty()) {
            llHaveDevice.setVisibility(View.GONE);
            llNoDevice.setVisibility(View.VISIBLE);
        } else {
            llHaveDevice.setVisibility(View.VISIBLE);
            llNoDevice.setVisibility(View.GONE);
        }
    }

}
